//
//  HeadPageViewController.m
//  EarnBao
//
//  Created by xiaohui on 15/2/5.
//  Copyright (c) 2015年 杭州赚宝科技有限公司. All rights reserved.
//

#import "HeadPageViewController.h"
#import "HeadPageCollectionViewCell.h"
#import "HotKindViewController.h"
#import "DetailViewController.h"
#import "HomePageProduct.h"
#import "FocusDetailViewController.h"
#import "EarnBao-API.h"
#import "Reachability.h"
#import "MBProgressHUD.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "AFNetworking.h"
#import "DownLoadData.h"
#import "UpLoadData.h"

@interface HeadPageViewController ()<DownLoadDataDelegate>
{
    int flag;  //设置控制抽屉拉出或推回
    int pageNumber;  //页码
    
    UISearchBar *_searchBar;
    NSMutableArray *m_focus2Array;
    MenuView *m_menuView;
    AllMenuView *m_allMenuView;
}
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) Reachability *whole_conn;
@property (nonatomic, retain) MBProgressHUD *hud;
@property (nonatomic ,retain) NSMutableArray *waterfallArray;

@end

@implementation HeadPageViewController

//销毁通知
- (void)dealloc
{
    [self.whole_conn stopNotifier];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//数据加载完成之前显示的菊花圈
- (void)setProgressHud
{
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [_hud show:YES];
}

//构建子视图
- (void)setSubviews
{
    //在默认导航条的位置创建一个高64的等屏宽的透明view，这么做是为了处理手动滑动焦点图片时出现的图片移位的蛋疼情况！
    UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 64)];
    [self.view addSubview:aView];
    
    //瀑布流主体
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(self.view.bounds.size.width*11/24, self.view.bounds.size.width*11/18);
    flowLayout.sectionInset = UIEdgeInsetsMake(self.view.bounds.size.width/48, self.view.bounds.size.width/48, self.view.bounds.size.width/48, self.view.bounds.size.width/48);
    
    //添加瀑布流头部:headerView(其上可以添加其他控件以响应事件)
    flowLayout.headerReferenceSize = CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.width/3 + self.view.bounds.size.width*132/315);
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, kMainScreen_Width, kMainScreen_Height - 64 - 49) collectionViewLayout:flowLayout];
    _collectionView.delegate = self;  //设置代理
    _collectionView.dataSource = self;  //设置数据源
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1.0];
    [self.view addSubview:_collectionView];
}

//视图加载完成
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.tintColor=WHITE_COLOR;
    
    UIView *naviView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, kMainScreen_Width, 45)];
    //设置导航条图片
    UIImageView *navImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 8,70,30)];
    navImgView.image = [UIImage imageNamed:@"naviBack"];
    [naviView addSubview:navImgView];
    
    _searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(75, 0, 160, 44)];
    [_searchBar setBackgroundColor:[UIColor clearColor]];
    _searchBar.searchBarStyle = UISearchBarStyleMinimal;
    _searchBar.placeholder=@"在15000款产品中搜索";
    _searchBar.delegate=self;
    [naviView addSubview:_searchBar];
    
    UITextField *searchField = [_searchBar valueForKey:@"_searchField"];
    [searchField setBackgroundColor:[UIColor clearColor]];
    [searchField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    [searchField setFont:[UIFont systemFontOfSize:11]];
    [searchField setTextColor:WHITE_COLOR];
    UIImage *image = [UIImage imageNamed: @"search"];
    UIImageView *iView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
    iView.image=image;
    searchField.leftView = iView;
    
    
    UIButton *signBtn = [[UIButton alloc] initWithFrame:CGRectMake(kMainScreen_Width*0.8, 0, 55, 24)];
    [signBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [signBtn setImage:[UIImage imageNamed:@"signImage"] forState:UIControlStateNormal];
    [signBtn addTarget:self action:@selector(signBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:signBtn];
    
   self.navigationItem.titleView=naviView;
    
    //调用构建子视图的方法
    [self setSubviews];
    
    //初始化对象数组
    self.waterfallArray = [[NSMutableArray alloc] initWithCapacity:0];
    
    //页码初始值设置为2
    pageNumber = 2;
    
    //视图加载完成就请求数据为了做缓存
    
    [self getMenuData];
    [self loadData];
    [self getDataOfFocusImg];
    
//    [self getDataOfHot];
    //[self getDataOfHotKinds];
    
    //上传版本号
    [self upVersion];
    
    //注册一个通知用来实时监测网络状态的改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
    //创建一个全局的网络对象
     self.whole_conn = [Reachability reachabilityForInternetConnection];
    //开启通知
    [self.whole_conn startNotifier];
    
    
    //监测网络状态的变化
    [self networkStateChange];
}

#pragma mark ---实时监测网络状态的改变(一切数据请求和数据显示的相关处理均以网络状态的不同为基准进行！)---

//网络状态改变
- (void)networkStateChange
{
    [self checkNetworkState];
}

//检查网络状态
- (void)checkNetworkState
{
    //1.创建wifi网络对象
    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
        
    //2.创建手机网络对象(2G/3G/4G，也就是平时常说的手机流量)
    Reachability *conn = [Reachability reachabilityForInternetConnection];
        
    //3.判断当前app的网络连接状态，通常分为以下三种情况：
    
    //有wifi连接(包括两种情况：1.只有wifi  2.手机网络和wifi同时存在，此时wifi会自动替换掉手机网络)
    if ([wifi currentReachabilityStatus] != NotReachable) {
        
        [self setProgressHud];
        [self addHeader];
        [self addFooter];
        [_hud hide:YES];
    }
    
    //只有手机网络
    if ([conn currentReachabilityStatus] != NotReachable && [wifi currentReachabilityStatus] == NotReachable) {
        
        [self setProgressHud];
        [self addHeader];
        [self addFooter];
        [_hud hide:YES];
    }
    
    //无网络连接(首次使用或上次使用时手动清理过缓存，这两种情况都说明没有缓存资源！)
    if (([wifi currentReachabilityStatus] == NotReachable) && ([conn currentReachabilityStatus] == NotReachable)) {
        
        NSString *cachPath = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingFormat:@"/Caches"];
        NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
        
        //模拟器检测文件数为7，真机检测文件数为8，故取10作为判断标准！
        if ([files count] < 10) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"没有发现可用的缓存资源，请连接网络哦！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alert show];
        }
    }
}

#pragma mark ---将当前使用的app的版本号上传给服务器端---

- (void)upVersion
{
    UpLoadData *handle = [UpLoadData shareDataHandle];
    [handle upLoadDataWithURL:kHomePage_ProductList];
}

#pragma mark ---从服务器请求数据，用代理刷新数据---

//加载数据
- (void)loadData
{
    //初始化请求对象
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    //GET请求(也可以用POST请求)
    [manager GET:kHomePage_ProductList parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         //视图和数据只能合一起写，若分开写浏览页面后会出现响应异常！
         
         __block HeadPageViewController *headPageVC = self;
         
         NSDictionary *sourceDic = responseObject[@"products"];
         
         for (NSDictionary *dic in sourceDic) {
             
             HomePageProduct *homePageProduct = [[HomePageProduct alloc] init];
             [homePageProduct setValuesForKeysWithDictionary:dic];
             [self.waterfallArray addObject:homePageProduct];
             
         }
         [headPageVC.collectionView reloadData];
     }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             
             NSLog(@"服务器出错了！相关错误信息是:%@",error);
         }];
}

//加载更多数据
- (void)loadMoreData
{
    NSString *pageNumberString=[NSString stringWithFormat:@"&page=%d",pageNumber];
    NSString *urlString = [kHomePage_ProductList stringByAppendingString:pageNumberString];
    
    DownLoadData *handle = [DownLoadData shareDataHandle];
    //设置代理
    handle.delegate = self;
    [handle downLoadDataWithURL:urlString key:@"products" model:@"HomePageProduct" results:self.waterfallArray];
    
    //加载更多数据执行一次后页码累加1
    pageNumber ++;
}

//刷新数据(handle对象成为代理后实现协议中的方法)
- (void)refresh
{
    [self.collectionView reloadData];
}

#pragma mark ---下拉刷新数据，上拉加载更多数据---

//添加页头下拉刷新控件
- (void)addHeader
{
    __unsafe_unretained typeof(self) vc = self;
    
    //进入刷新状态就会回调这个Block
    [self.collectionView addHeaderWithCallback:^{
        
        [vc.collectionView reloadData];  //刷新数据
        
        //模拟延迟刷新数据，1秒后才调用，也就是转圈的动作持续1秒！
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [vc.collectionView headerEndRefreshing];  //结束刷新动作
        });
    }];
}

//添加页脚上拉加载控件
- (void)addFooter
{
    __unsafe_unretained typeof(self) vc = self;
    
    //进入加载状态就会回调这个Block
    [self.collectionView addFooterWithCallback:^{
        
        [self loadMoreData];  //加载更多数据
        
        //模拟延迟加载数据，2秒后才调用，也就是转圈的动作持续2秒！
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self.collectionView footerEndRefreshing];  //结束刷新动作
        });
    }];
}

#pragma mark ----网络请求并解析接口中焦点部分的数据----
- (void)getDataOfFocusImg
{
    //app版本号
    NSDictionary *inforDic = [[NSBundle mainBundle] infoDictionary];
    NSString *app_version = inforDic[@"CFBundleShortVersionString"];
    
    //初始化将要上传到服务器的的数据字典
    NSDictionary *parameters = @{@"app_version": app_version};
    
    //初始化请求对象
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    //GET请求(也可以用POST请求)
    [manager GET:kHomePage_FocusHotAllKinds parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        //视图和数据只能合一起写，若分开写浏览页面后会出现响应异常！
        
        __block HeadPageViewController *headPageVC = self;
        
        NSMutableArray *imageArray = [[NSMutableArray alloc] initWithCapacity:0];  //焦点图片数组
        NSMutableArray *focus_urlArray = [[NSMutableArray alloc] initWithCapacity:0];  //焦点url字符串数组
        
        NSDictionary *sourceDic = responseObject[@"index"];
        NSArray *focusArray = sourceDic[@"focus"];
        NSArray *focus2Array = sourceDic[@"focus2"];
        m_focus2Array=[NSMutableArray arrayWithArray:focus2Array];
        [self getDataOfHot];
        for (NSDictionary *dic in focusArray) {
            
            NSString *img = dic[@"img"];
            [imageArray addObject:img];
        
            NSString *url = dic[@"url"];
            [focus_urlArray addObject:url];
        }
        
        NSArray *imagesURLStrings=[NSArray arrayWithArray:imageArray];
        
        SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, kNAV_HEIGHT, kMainScreen_Width, kMainScreen_Width/3) imageURLStringsGroup:nil];
        cycleScrollView.backgroundColor=WHITE_COLOR;
        cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleClassic;
        cycleScrollView.delegate = self;
        cycleScrollView.autoScrollTimeInterval = 4.0;
        [headPageVC.collectionView addSubview:cycleScrollView];
        //             --- 模拟加载延迟
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            cycleScrollView.imageURLStringsGroup = imagesURLStrings;
        });

        
        //将url保存到沙盒的Documents文件夹的focus_url.plist文件中，便于详情页取url
        
        //1.获得沙盒的根目录
        NSString *home = NSHomeDirectory();
        
        //2.获取Documents文件夹的路径
        NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];
        
        //3.新建自定义文件的路径
        NSString *filepath = [docPath stringByAppendingPathComponent:@"focus_url.plist"];
        
        //4.写入自定义文件
        [focus_urlArray writeToFile:filepath atomically:YES];
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"服务器出错了！相关错误信息是:%@",error);
    }];
}

#pragma mark ----网络请求并解析接口中热门分类部分的数据----
-(void)getMenuData
{
    __block HeadPageViewController *headPageVC = self;
    NSArray *tabArray=@[@"全部",@"女装", @"男装",@"居家",@"美容"];
    m_menuView=[MenuView alloc];
    [m_menuView setMenutitles:[NSArray arrayWithArray:tabArray]];
    [m_menuView setCurrentSelectedIndex:0];
    [m_menuView setDelegate:self];
    m_menuView=[m_menuView initWithArray:tabArray];
    [m_menuView setFrame:CGRectMake(0, 0, kMainScreen_Width, kNAV_HEIGHT)];
    [headPageVC.collectionView addSubview:m_menuView];
}
- (void)getDataOfHotKinds
{
    //app版本号
    NSDictionary *inforDic = [[NSBundle mainBundle] infoDictionary];
    NSString *app_version = inforDic[@"CFBundleShortVersionString"];
    
    //初始化将要上传到服务器的的数据字典
    NSDictionary *parameters = @{@"app_version": app_version};
    
    //初始化请求对象
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    //GET请求(也可以用POST请求)
    [manager GET:kHomePage_FocusHotAllKinds parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        //视图和数据只能合一起写，若分开写浏览页面后会出现响应异常！
        
        __block HeadPageViewController *headPageVC = self;
        
        NSMutableArray *imageUrlArray = [[NSMutableArray alloc] initWithCapacity:0];
        NSMutableArray *hotKind_nameArray = [[NSMutableArray alloc] initWithCapacity:0];
        NSMutableArray *hotKind_urlArray = [[NSMutableArray alloc] initWithCapacity:0];  //热门分类的url字符串数组
        
        NSDictionary *sourceDic = responseObject[@"index"];
        NSArray *listArray = sourceDic[@"navi"];
        for (NSDictionary *dic in listArray) {
        
            NSString *imgUrl = dic[@"img"];
            [imageUrlArray addObject:imgUrl];
            
            NSString *name = dic[@"name"];
            [hotKind_nameArray addObject:name];
            
            //转换数据格式(将汉字转化成url类型)
            NSString *encodedString = [name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSString *urlString = [NSString stringWithFormat:@"http://open.zhuanbao.com/app/index.php?go=ios&do=product_list&classify=%@",encodedString];
            [hotKind_urlArray addObject:urlString];
            
            
            UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.width/3+kNAV_HEIGHT, self.view.bounds.size.width, headPageVC.collectionView.bounds.size.width*132/315)];
            myView.backgroundColor = [UIColor whiteColor];
            [headPageVC.collectionView addSubview:myView];
            
            for (int i =0; i<imageUrlArray.count; i++) {
                if (i<4) {
                    _imgLView = [[ImgLView alloc] initWithFrame:CGRectMake(headPageVC.collectionView.bounds.size.width/9*(2*(i+1)-1), headPageVC.collectionView.bounds.size.width/30, headPageVC.collectionView.bounds.size.width/9, headPageVC.collectionView.bounds.size.width*4/27)];
                }
                if (i >=4) {
                    _imgLView = [[ImgLView alloc] initWithFrame:CGRectMake(headPageVC.collectionView.bounds.size.width/9*(2*(i+1)-9), headPageVC.collectionView.bounds.size.width/15 + headPageVC.collectionView.bounds.size.width*4/27, headPageVC.collectionView.bounds.size.width/9, headPageVC.collectionView.bounds.size.width*4/27)];
                }
                _imgLView.tag = 10000 + i;
                [_imgLView.imageView sd_setImageWithURL:[NSURL URLWithString:imageUrlArray[i]]];
                _imgLView.label.text = hotKind_nameArray[i];
                [myView addSubview:_imgLView];
                
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hotKindsImageViewTap:)];
                _imgLView.userInteractionEnabled = YES;
                [_imgLView addGestureRecognizer:tap];
            }
        }
        //将url保存到沙盒的Documents文件夹的hotKind_url.plist文件中，便于详情页取url
        
        //1.获得沙盒的根目录
        NSString *home = NSHomeDirectory();
        
        //2.获取Documents文件夹的路径
        NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];
        
        //3.新建自定义文件的路径
        NSString *filepath1 = [docPath stringByAppendingPathComponent:@"hotKind_url.plist"];
        NSString *filepath2 = [docPath stringByAppendingPathComponent:@"hotKind_name.plist"];
        
        //4.写入自定义文件
        [hotKind_urlArray writeToFile:filepath1 atomically:YES];
        [hotKind_nameArray writeToFile:filepath2 atomically:YES];
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             
        NSLog(@"服务器出错了！相关错误信息是:%@",error);
    }];
}
-(void)getDataOfHot
{
    NSMutableArray *imgArray=[NSMutableArray array];
    for (NSDictionary *dic in m_focus2Array) {
        NSString *img = dic[@"img"];
        [imgArray addObject:img];
    }
    
    __block HeadPageViewController *headPageVC = self;
    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.width/3, self.view.bounds.size.width, headPageVC.collectionView.bounds.size.width*132/315)];
    myView.backgroundColor = [UIColor whiteColor];
    [headPageVC.collectionView addSubview:myView];
    
    UIView *backView=[[UIView alloc]initWithFrame:CGRectMake(0, 5, kMainScreen_Width, myView.frame.size.height-10)];
    CGSize backViewSize=backView.frame.size;
    
    UITapGestureRecognizer *gesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImgView:)];
    
    UIImageView *bigImgView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 5, backViewSize.width*0.35, backViewSize.height)];
    //[bigImgView setImage:[UIImage imageNamed:@"Default.png"]];
    [bigImgView sd_setImageWithURL:imgArray[0]];
    bigImgView.userInteractionEnabled=YES;
    [bigImgView setTag:0];
    [bigImgView addGestureRecognizer:gesture];
    [myView addSubview:bigImgView];
    
    CGFloat itemW=kMainScreen_Width*0.325-2;
    CGFloat itemH=backViewSize.height*0.5-1;

    for (int i=0; i<4; i++) {
        int row=i/2;
        int colum=i%2;
        UIImageView *smallView=[[UIImageView alloc]init];
        [smallView setFrame:CGRectMake(kMainScreen_Width*0.35+(itemW+2)*colum+2, itemH*row+2*row+5, itemW, itemH)];
        smallView.userInteractionEnabled=YES;
        UITapGestureRecognizer *gesture1=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImgView:)];
        [smallView addGestureRecognizer:gesture1];
        [smallView setTag:i+1];
        [smallView sd_setImageWithURL:imgArray[i+1]];
        //[smallView setImage:[UIImage imageNamed:@"Default.png"]];
        [myView addSubview:smallView];
    }
}
-(void)tapImgView:(UIGestureRecognizer *)gesture
{
    NSMutableArray *urlArray=[NSMutableArray array];
    for (NSDictionary *dic in m_focus2Array) {
        NSString *url = dic[@"url"];
        [urlArray addObject:url];
    }
    FocusDetailViewController *focusDetailVC=[[FocusDetailViewController alloc] init];
    focusDetailVC.hidesBottomBarWhenPushed=YES;
    focusDetailVC.urlString=urlArray[gesture.view.tag];
    [self.navigationController pushViewController:focusDetailVC animated:YES];
}
#pragma mark ---collectionView的代理方法---

//设置瀑布流的子模块个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [_waterfallArray count];
}

//显示瀑布流内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    [collectionView registerClass:[HeadPageCollectionViewCell class] forCellWithReuseIdentifier:cellIdentifier];
    HeadPageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    HomePageProduct *homePageProduct = _waterfallArray[indexPath.row];
    cell.homePageProduct = homePageProduct;
    
    if ([homePageProduct.free_post isEqualToString:@"1"]) {
        cell.free_post_nameLabel.text = [NSString stringWithFormat:@"[包邮]%@",homePageProduct.name];
    }
    if ([homePageProduct.shop_type isEqualToString:@"B"]) {
        cell.shop_typeImageView.image = [UIImage imageNamed:@"tmall.png"];
    }
    
    //给“市场价格”添加删除线 
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:cell.market_priceLabel.text];
    NSUInteger length = [cell.market_priceLabel.text length];
    [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, length)];
    [attri addAttribute:NSStrikethroughColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, length)];
    [cell.market_priceLabel setAttributedText:attri];
    
    [_hud hide:YES];  //数据加载完成后将菊花圈隐藏掉！
    
    return cell;
}

//点击瀑布流中的item跳转至对应的页面
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DetailViewController *detailVC = [[DetailViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:detailVC];
    HomePageProduct *homePageProduct = _waterfallArray[indexPath.row];
    detailVC.urlString = homePageProduct.url;
    [self presentViewController:nav animated:YES completion:nil];
   // [self.navigationController pushViewController:detailVC animated:YES];
}

//点击“热门分类”跳转至对应的页面
-(void)hotKindsImageViewTap:(UITapGestureRecognizer *)tap
{
    //1.获得沙盒根路径
    NSString *home = NSHomeDirectory();
    
    //2.document路径
    NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];
    
    //3.文件路径
    NSString *filepath1 = [docPath stringByAppendingPathComponent:@"hotKind_url.plist"];
    NSString *filepath2 = [docPath stringByAppendingPathComponent:@"hotKind_name.plist"];
    
    //4.读取出url字符串数组
    NSArray *hotKind_urlArray = [NSArray arrayWithContentsOfFile:filepath1];
    NSArray *hotKind_nameArray = [NSArray arrayWithContentsOfFile:filepath2];
    
    
    HotKindViewController *hotKindVC=[[HotKindViewController alloc] init];
    
    ImgLView *imgLView = (ImgLView *)tap.view;  //找到轻拍手势作用所在的视图！！！
    
    long tagNumber = imgLView.tag - 10000;
    
    if (tagNumber==0) {
        hotKindVC.urlString = hotKind_urlArray[0];
        hotKindVC.titleString = hotKind_nameArray[0];
    }
    else if (tagNumber==1) {
        hotKindVC.urlString = hotKind_urlArray[1];
        hotKindVC.titleString = hotKind_nameArray[1];
    }
    else if (tagNumber==2) {
        hotKindVC.urlString = hotKind_urlArray[2];
        hotKindVC.titleString = hotKind_nameArray[2];
    }
    else if (tagNumber==3) {
        hotKindVC.urlString = hotKind_urlArray[3];
        hotKindVC.titleString = hotKind_nameArray[3];
    }
    else if (tagNumber==4) {
        hotKindVC.urlString = hotKind_urlArray[4];
        hotKindVC.titleString = hotKind_nameArray[4];
    }
    else if (tagNumber==5) {
        hotKindVC.urlString = hotKind_urlArray[5];
        hotKindVC.titleString = hotKind_nameArray[5];
    }
    else if (tagNumber==6) {
        hotKindVC.urlString = hotKind_urlArray[6];
        hotKindVC.titleString = hotKind_nameArray[6];
    }
    else {
        hotKindVC.urlString = hotKind_urlArray[7];
        hotKindVC.titleString = hotKind_nameArray[7];
    }
    
    [self.navigationController pushViewController:hotKindVC animated:YES];
}
#pragma mark - SDCycleScrollViewDelegate

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    [self focusImageViewTap:index];
}
//点击“焦点”跳转至对应的页面
-(void)focusImageViewTap:(NSInteger)index
{
    //1.获得沙盒根路径
    NSString *home = NSHomeDirectory();
    
    //2.document路径
    NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];
    
    //3.文件路径
    NSString *filepath = [docPath stringByAppendingPathComponent:@"focus_url.plist"];
    //4.读取出url字符串数组
    NSArray *focus_urlArray = [NSArray arrayWithContentsOfFile:filepath];
    FocusDetailViewController *focusDetailVC=[[FocusDetailViewController alloc] init];
    focusDetailVC.hidesBottomBarWhenPushed=YES;
    focusDetailVC.urlString=focus_urlArray[index];
    [self.navigationController pushViewController:focusDetailVC animated:YES];
}


#pragma mark action 
-(void)signBtnClicked:(UIButton *)button
{
    NSLog(@"签到");
}

#pragma mark search bar delegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    return YES;
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    return YES;
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
   NSLog(@"%@",searchBar.text);
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}
#pragma mark clickMenuDelegate
-(void)clickMenuAt:(NSInteger)index
{
    if (index>4) {
        
    }
}
-(void)showAllMenuWith:(BOOL)isMore
{
    if (m_allMenuView==nil) {
        NSArray *tabArray=@[@"全部",@"女装", @"男装",@"居家",@"美容",@"女装", @"男装",@"居家",@"美容"];
        int num=kMainScreen_Width*0.94/40;
        NSInteger row=tabArray.count/num;//行
        CGFloat height=30*row+70;
        m_allMenuView=[[AllMenuView alloc]initWithFrame:CGRectMake(0, 64+kNAV_HEIGHT, kMainScreen_Width, height)];
        
        [m_allMenuView initWithArray:tabArray];
    }
    if (isMore) {
        [self.view addSubview:m_allMenuView];
    }else{
        [m_allMenuView removeFromSuperview];
    }
}
@end











